package com.example.treehole.ui.model

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class UserViewModel(application: Application) : AndroidViewModel(application) {

    private val userPreferences = UserPreferences(application.applicationContext)

    private val _userId = MutableStateFlow<Int?>(null)
    val userId: StateFlow<Int?> = _userId

    private val _jwlToken = MutableStateFlow<String>("")
    val jwlToken: StateFlow<String> = _jwlToken

    private val _isLoggedIn = MutableStateFlow<Boolean>(false)
    val isLoggedIn:StateFlow<Boolean> = _isLoggedIn

    init {
        if (userPreferences.isLoggedIn()) {
            _userId.value = userPreferences.getUserId()
            _jwlToken.value = userPreferences.getJwlToken()
            _isLoggedIn.value = true
        }
    }

    fun login(userId: Int, jwlToken: String) {
        userPreferences.saveLoginInfo(userId, jwlToken)
        _userId.value = userId
        _jwlToken.value = jwlToken
        _isLoggedIn.value = true
    }

    fun logout() {
        userPreferences.clearLoginInfo()
        _userId.value = null
        _jwlToken.value = ""
        _isLoggedIn.value = false
    }
}